/****************************************************************
 * Copyright (c) 2007 Besture All Rights Reserved.
 * 
 * File Name        :OutputFiles.cs
 * 
 * Created          :2007/05/17
 * Original Author  :Zhigang Chi 
 * 
 * ------------------------------------------------------------
 * MODIFICATION HISTORY
 * ------------------------------------------------------------
 * When     Who     Why
 * ------------------------------------------------------------
 * 
 *
 ****************************************************************/

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.IO;
using System.Web;
using System.Web.UI;

using Besture.Common.Definition;

namespace Besture.Common.OutputFiles
{
    public class OutputFiles
    {
        private const int HEADER_COLUMNS = 2;
        private const string NEW_LINE = "\r\n";
        private const string END = "\n";

        /// <summary>
        /// output HTML file with data in ldtText
        /// </summary>
        /// <param name="ldtText">data to be output</param>
        /// <param name="lsFileName">file name</param>
        public static void OutputHTMLFile(DataTable ldtText, String lsFileName)
        {
            String lsFilePath = AppSettings.GetTempFilePath() + lsFileName;
            String[] lsContent = new String[ldtText.Rows.Count];
            for (int i = 0; i < ldtText.Rows.Count; i++)
            {
                lsContent[i] = ldtText.Rows[i][0].ToString().Trim();
            }
            WriteToFile(lsFilePath, lsContent, ldtText.Rows.Count);
        }

        private static void WriteToFile(String lsFilePath, String[] lsContent, int lnCount)
        {
            StreamWriter loRW = new StreamWriter(lsFilePath, true, Encoding.GetEncoding(Constants.CHAR_STANDARD));
            for (int i = 0; i < lnCount; i++)
            {
                loRW.WriteLine(lsContent[i]);
            }
            loRW.Close();
        }

        /// <summary>
        /// Output the file
        /// </summary>
        /// <param name="lsbContext">file's context</param>
        /// <param name="lsFileName">file's name</param>
        public static void WriteToHTMLFile(StringBuilder lsbContext, string lsFileName)
        {
            try
            {
                string lsPath = AppSettings.GetTempFilePath();

                using (StreamWriter loRW = new StreamWriter((lsPath + lsFileName), false, Encoding.GetEncoding(Constants.CHAR_STANDARD)))
                {
                    loRW.Write(lsbContext.ToString());
                    loRW.Close();
                }
            }
            catch (System.Exception ee)
            {
                Besture.Common.Logging.AppLogger.TraceLog("WriteToHTMLFile error");
                Besture.Common.Logging.AppLogger.TraceLog(ee.StackTrace);
            }
        }

        /// <summary>
        /// Output the Photo file
        /// </summary>
        /// <param name="loPhoto">file's context</param>
        /// <param name="lsFileName">file's name</param>
        public static void WriteToJPEGFile(object loPhoto, string lsFileName)
        {
            try
            {
                string lsPath = AppSettings.GetTempFilePath();

                byte[] lbImage = (byte[])loPhoto;
                if (lbImage.Length > 0)
                {
                    using (FileStream loFstream = new FileStream(lsPath + lsFileName, FileMode.Create))
                    {
                        loFstream.Write(lbImage, 0, lbImage.Length);
                        loFstream.Flush();
                        loFstream.Close();
                    }
                }
            }
            catch (System.Exception ee)
            {
                Besture.Common.Logging.AppLogger.TraceLog("WriteToJPEGFile error");
                Besture.Common.Logging.AppLogger.TraceLog(ee.StackTrace);
            }
        }

        /// <summary>
        /// output CSV file with data in ldtText
        /// </summary>
        /// <param name="page">page</param>
        /// <param name="ldtText">data to be output</param>
        /// <param name="lsFileName">file name</param>
        public static void OutputCSVFile(Page page, DataTable ldtText, String lsFileName)
        {
            OutputCSVFile(page, ldtText, lsFileName, null, null);
        }

        /// <summary>
        /// output CSV file with data in ldtText
        /// </summary>
        /// <param name="page">page</param>
        /// <param name="ldtText">data to be output</param>
        /// <param name="lsFileName">file name</param>
        /// <param name="lsTitle">title: string[]</param>
        public static void OutputCSVFile(Page page, DataTable ldtText, String lsFileName, String[] lsTitle)
        {
            OutputCSVFile(page, ldtText, lsFileName, lsTitle, null);
        }

        /// <summary>
        /// output CSV file with data in ldtText
        /// </summary>
        /// <param name="page">page</param>
        /// <param name="ldtText">data to be output</param>
        /// <param name="lsFileName">file name</param>
        /// <param name="lsTitle">title: string[]</param>
        /// <param name="lsTitle">header: string[][2]</param>
        public static void OutputCSVFile(Page page, DataTable ldtText, String lsFileName, String[] lsTitle, String[][] lsHeader)
        {
            StringBuilder contents = new StringBuilder();

            if (lsHeader != null)
            {
                // write the header.
                for (int m = 0; m < lsHeader.Length; m++)
                {
                    contents.Append(lsHeader[m][0] + Constants.CSV_COMMA_STRING + Constants.CSV_DOUBLE_QUOTATION +
                        lsHeader[m][1].Replace(Constants.CSV_DOUBLE_QUOTATION, Constants.CSV_D_DOUBLE_QUOTATION) + Constants.CSV_DOUBLE_QUOTATION);
                    contents.Append(NEW_LINE);
                }
            }

            if (lsTitle != null)
            {
                // add title to csv
                foreach (string str in lsTitle)
                {
                    contents.Append(str + Constants.CSV_COMMA_STRING);
                }
                contents.Remove(contents.Length - 1, 1);
                contents.Append(NEW_LINE);
            }

            for (int i = 0; i < ldtText.Rows.Count; i++)
            {
                for (int j = 0; j < ldtText.Columns.Count; j++)
                {
                    /***********MODIFY START: 2007/11/1  yuyuanlong********/
                    // OLD SOURCE 
                    //contents.Append(Constants.CSV_DOUBLE_QUOTATION + ldtText.Rows[i][j].ToString().Trim().Replace(NEW_LINE, END));

                    // NEW SOURCE
                    contents.Append(Constants.CSV_DOUBLE_QUOTATION + ldtText.Rows[i][j].ToString().Trim().
                        Replace(Constants.CSV_DOUBLE_QUOTATION, Constants.CSV_D_DOUBLE_QUOTATION).Replace(NEW_LINE, END));
                    /***********MODIFY END: 2007/11/1  yuyuanlong**********/
                    if (j < ldtText.Columns.Count - 1)
                    {
                        contents.Append(Constants.CSV_DOUBLE_QUOTATION + Constants.CSV_COMMA_STRING);
                    }
                    else
                    {
                        contents.Append(Constants.CSV_DOUBLE_QUOTATION);
                    }
                }
                contents.Append(NEW_LINE);
            }

            // download file
            DownloadFile(page, contents.ToString(), lsFileName);
        }

        public static void DownloadFile(System.Web.UI.Page page, string stringContent, string fileName)
        {
            page.Response.Clear();
            page.Response.ClearHeaders();
            page.Response.ContentType = "application/csv";
            page.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
            page.Response.ContentEncoding = Encoding.GetEncoding("GB2312");
            page.Response.Write(stringContent);
            page.Response.End();
        }
    }
}
